/**
 * 
 * LegendShop 多用户商城系统
 * 
 *  版权所有,并保留所有权利。
 * 
 */
package com.legendshop.oa.manager;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.multipart.MultipartFile;

import com.legendshop.oa.constants.Constants;
import com.legendshop.oa.constants.InvokeRetObj;
import com.legendshop.oa.constants.UploadFileConstants;
import com.legendshop.oa.constants.ValidateFileProcessor;
import com.legendshop.oa.exception.BusinessException;
import com.legendshop.oa.util.MD5Util;
import com.legendshop.util.AppUtils;
import com.legendshop.util.DateUtil;
import com.legendshop.util.JSONUtil;

/**
 * 远程文件管理
 *
 */
public class HttpAttachmentManagerImpl extends CommonAttachmentManagerImpl implements InitializingBean {

	private String systemToken;// 系统参数

	/**
	 * 文件流形式 上传,目前只是支持一个文件上传
	 */
	@Override
	public String upload(InputStream is, String fileName, long fileSize){
		if (!ValidateFileProcessor.validateFile(fileName, fileSize)) {
			throw new BusinessException("file format error: " + fileName);
		}
		Map<String, InputStream> insMap = new HashMap<String, InputStream>();
		insMap.put(fileName, is);
		String ret = formUpload(UploadFileConstants.UPLOAD_FILE_URL, fileName, insMap);
		Object result = getObjectFromResult(fileName, ret); // 上传的功能是支持多个文件上传的,但是这里只是支持一个
		if (AppUtils.isNotBlank(result)) {
			List<String> pathList = (List<String>) result;
			return pathList.get(0);
		}
		return Constants.PHOTO_FORMAT_ERR;
	}

	/**
	 * For Spring mvc文件上传
	 */
	@Override
	public String upload(MultipartFile file){
		if (file == null) {
			throw new BusinessException("file is null");
		}
		String fileName = file.getOriginalFilename();
		try {
			return upload(file.getInputStream(), fileName, file.getSize());
		} catch (IOException e) {
			throw new BusinessException(e, "file format error: " + fileName);
		}
	}

	/**
	 * 真实删除图片
	 * 
	 * @param fileName
	 *            文件路径
	 * @return 0 成功 -1 删除失败 1 没有文件 2 其他异常
	 */
	@Override
	public int deleteTruely(String fileName) {
		if (AppUtils.isBlank(fileName)) {
			return 0;
		}

		String ret = sendGet(UploadFileConstants.DELETE_FILE_URL,fileName, "fileName=" + fileName);
		int result = 0;
		try {
			result = getReturnCodeFromResult(fileName, ret);
		} catch (Exception e) {
			log.error("", e);
		}
		return result;
	}

	/**
	 * 上传图片
	 * 
	 * @param urlStr
	 *            不肯能为空的
	 * @param fileMap
	 * @return
	 */
	private String formUpload(String urlStr, String fileName, Map<String, InputStream> insMap) {
		String res = "[]";
		HttpURLConnection conn = null;
		String BOUNDARY = "---------------------------58487568765418"; // boundary就是request头和上传文件内容的分隔符
		try {
			URL url = new URL(urlStr);
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(60000);
			conn.setReadTimeout(60000);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
			conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

			// 增加头部安全信息
			String dateStr = DateUtil.DateToString(new Date(), "yyyy-MM-dd HH:MM:SS");
			conn.setRequestProperty("ls-time", dateStr);

			String securityResult = MD5Util.toMD5(systemToken + dateStr);
			conn.setRequestProperty("ls-security", securityResult);

			OutputStream out = new DataOutputStream(conn.getOutputStream());

			// file
			Iterator<Entry<String, InputStream>> iter = insMap.entrySet().iterator();
			while (iter.hasNext()) {
				Map.Entry<String, InputStream> entry = (Map.Entry<String, InputStream>) iter.next();
				String inputName = (String) entry.getKey();
				InputStream is = (InputStream) entry.getValue();
				String contentType = "application/octet-stream";

				StringBuffer strBuf = new StringBuffer();
				strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
				strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + inputName + "\"\r\n");
				strBuf.append("Content-Type:" + contentType + "\r\n\r\n");

				out.write(strBuf.toString().getBytes());

				DataInputStream in = new DataInputStream(is);
				int bytes = 0;
				byte[] bufferOut = new byte[1024];
				while ((bytes = in.read(bufferOut)) != -1) {
					out.write(bufferOut, 0, bytes);
				}
				in.close();
			}

			byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
			out.write(endData);
			out.flush();
			out.close();

			// 读取返回数据
			StringBuffer strBuf = new StringBuffer();
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				strBuf.append(line).append("\n");
			}
			res = strBuf.toString();
			reader.close();
			reader = null;
		} catch (Exception e) {
			log.error("formUpload error. " + urlStr, e);
		} finally {
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
		}
		return res;
	}

	private String sendGet(String url, String fileName, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			
			
			// 增加头部安全信息
			String dateStr = DateUtil.DateToString(new Date(), "yyyy-MM-dd HH:MM:SS");
			connection.setRequestProperty("ls-time", dateStr);

			String securityResult = MD5Util.toMD5(systemToken  + dateStr);
			connection.setRequestProperty("ls-security", securityResult);
			
			
			// 建立实际的连接
			connection.connect();
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			log.error("sendGet error！", e);
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				log.error("close instream error！", e2);
			}
		}
		return result;
	}

	/**
	 * 从返回结果中获取最终的结果,并做好显示记录
	 * 
	 * @return
	 */
	private Object getObjectFromResult(String fileName, String ret) {
		InvokeRetObj returnObj = JSONUtil.getObject(ret, InvokeRetObj.class); // 支持错误原因并做好打印显示工作
		if (returnObj != null) {
			if (returnObj.isFlag()) {// 上传成功
				return returnObj.getObj(); // 上传的功能是支持多个文件上传的,但是这里只是支持一个
			} else {
				log.warn("File process failed,  file name is {}, msg is {}", fileName, returnObj.getMsg());
			}
		} else {
			log.warn("File process failed, file name is {}", fileName);
		}
		return null;
	}

	/**
	 * 从返回结果中获取最终的结果,并做好显示记录
	 * 
	 * @return
	 */
	private int getReturnCodeFromResult(String fileName, String ret) {
		InvokeRetObj returnObj = JSONUtil.getObject(ret, InvokeRetObj.class); // 支持错误原因并做好打印显示工作
		if (returnObj != null) {
			if (returnObj.isFlag()) {// 上传成功
				return returnObj.getRetCode();
			} else {
				log.warn("Delete file failed, file name is {}, msg is {}", fileName, returnObj.getMsg());
			}
		} else {
			log.warn("Delete file failed for unknow reason, file name is {}", fileName);
		}
		
		return 2;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		
	}

}